import {
  Request
} from "../../../utils/request.js";
const app = getApp();
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;

/**
 * 初始化数据
 */
function initData(that) {
  inputVal = '';

  msgList = [{
    speaker: 'customer',
    contentType: 'text',
    content: '好'
  },
  {
    speaker: 'server',
    contentType: 'text',
    content: '你好！'
  },
  {
    speaker: 'server',
    contentType: 'text',
    content: '邻家小卫邻家小卫邻家小卫邻家小邻家小卫邻家小卫邻家小卫邻家小'
  },
  {
    speaker: 'customer',
    contentType: 'text',
    content: '您好！'
  },
  {
    speaker: 'server',
    contentType: 'text',
    content: '欢迎来到知遇之音！'
  }
  ]
  that.setData({
    msgList,
    inputVal
  })
}

/**
 * 计算msg总高度
 */
// function calScrollHeight(that, keyHeight) {
//   var query = wx.createSelectorQuery();
//   query.select('.scrollMsg').boundingClientRect(function(rect) {
//   }).exec();
// }

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight: '100vh',
    inputBottom: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      options: options
    })
    this.uid = options.uid; //对方聊天id
    this.uimg = options.uimg; //对方聊天头像
    console.log(options);
    wx.setNavigationBarTitle({
      title: options.name
    })
    new Request('Zyconcern/wechatcontent').request(
      () => {
        return {
          openid: app.globalData.openid,
          uid: options.uid, //对象uid
          userid: app.globalData.userid, //用户id
        }
      },
      (res) => {
        this.setData({
          msgList: res.data.data,
          objectimage: this.uimg,
          uid: this.uid
        });
        this.setData({
          toView: 'msg-' + (this.data.msgList.length - 1),
        });
      }
    );

    if (options.listid != null) {
      /**
     * 上传用户已读消息 updateXiaoContent
     */
      new Request('Zyconcern/updateXiaoContent').request(
        () => {
          return {
            openid: app.globalData.openid,
            uid: options.uid, //对象uid
            listid: options.listid, //当前消息列表id，最新
            userid: app.globalData.userid, //用户id
          }
        },
        (res) => {

        }
      );
    }

  },

  /**
   * 跳转用户详情页面
   */
  gotoFriendInfo: function (event) {
    let userid = this.data.uid
    if (userid == '' || userid == undefined) {
      new Request().showToast('userId为空');
      return;
    }
    //游客不可查看用户详情信息
    if (app.globalData.loginCode == -1) {
      //用户未注册 提示跳转注册页面
      new Login().LoginDown();
      return;
    }
    wx.navigateTo({
      url: '/pages/zhaon_friendinfo/zhaon_friendinfo?userid=' + userid,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.intervalId = setInterval(() => {
      new Request('Zyconcern/wechatcontent').request(
        () => {
          return {
            openid: app.globalData.openid,
            uid: this.uid,
            userid: app.globalData.userid, //用户id
          }
        },
        (res) => {
          this.setData({
            msgList: res.data.data
          });

        }
      );
    }, 3000);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.intervalId);
    this.intervalId = '';
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 获取聚焦
   */
  focus: function (e) {
    //设置定时器 缓解键盘向上弹起的时候 提前获取位置定为了
    setTimeout(function () {
      this.setData({
        toView: 'msg-' + (this.data.msgList.length - 1),
        inputBottom: keyHeight + 'px'
      });
    }.bind(this), 500);

    keyHeight = e.detail.height;
    this.setData({
      scrollHeight: (windowHeight - keyHeight) + 'px'
    });
    //计算msg高度
    // calScrollHeight(this, keyHeight);

  },

  //失去聚焦(软键盘消失)
  blur: function (e) {
    this.setData({
      scrollHeight: '100vh',
      inputBottom: 0
    })
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    })

  },
  /**
   * 
   * 监听用户的输入
   *  
   */
   userinput: function (e) {
    this.setData({
      userinput: e.detail.value,
    })
    console.log(this.data.userinput)
   },

  /**
   * 发送点击监听
   */
  sendClick: function (e) {
    console.log(this.data.userinput)
    // if (this.data.userinput == '' || this.data.userinput == null || this.data.userinput == undefined) {
    //   wx.showToast({
    //     title: '不能发送空白信息',
    //     icon: 'none'
    //   })
    // }
    let msgList = this.data.msgList
    //判断msgList的长度小于3可以直接发消息,大于3,进入判断
    if (msgList.length >= 3) {
      //判断数组前3条是否为customer发送的,为否：可以发消息,为是：进入判断
      if (msgList[0].speaker == 'customer' && msgList[1].speaker == 'customer' && msgList[2].speaker == 'customer') {
        //判断数组的长度是否大于4,为否：说明只能发三条信息,为是：进入判断
        if (msgList.length >= 4) {
          //判断数组的第4条是否为customer发送的,为否：可发送消息,为是：只能发送三条信息
          if (msgList[3].speaker != 'customer') {
            console.log('可以发送信息')
            this.data.msgList.push({
              speaker: 'customer',
              contentType: 'text',
              content: this.data.userinput
            });
            inputVal = '';  //消息清空
            this.setData({
              msgList: this.data.msgList,
              inputVal,
              toView: 'msg-' + (this.data.msgList.length - 1)
            });
            new Request('Zyconcern/sendcontent').request(
              () => {
                return {
                  openid: app.globalData.openid,
                  uid: this.uid,
                  contentText: this.data.userinput,
                  userid: app.globalData.userid, //用户id
                }
              },
              (res) => {
      
              }
            );
          } else {
            console.log('只能发三条信息')
            wx.showToast({
              title: '对方首次回复前只能发三条消息哦',
              icon: 'none',
              duration: 2500
            })
          }
        } else {
          console.log('只能发三条信息')
          wx.showToast({
            title: '对方首次回复前只能发三条消息哦',
            icon: 'none',
            duration: 2500
          })
        }
      } else {
        console.log('可以发送信息')
        this.data.msgList.push({
          speaker: 'customer',
          contentType: 'text',
          content: this.data.userinput
        });
        inputVal = '';  //消息清空
        this.setData({
          msgList: this.data.msgList,
          inputVal,
          toView: 'msg-' + (this.data.msgList.length - 1)
        });
        new Request('Zyconcern/sendcontent').request(
          () => {
            return {
              openid: app.globalData.openid,
              uid: this.uid,
              contentText: this.data.userinput,
              userid: app.globalData.userid, //用户id
            }
          },
          (res) => {
  
          }
        );
      }
    } else {
      console.log('可以发送信息')
      this.data.msgList.push({
        speaker: 'customer',
        contentType: 'text',
        content: this.data.userinput
      });
      inputVal = '';  //消息清空
      this.setData({
        msgList: this.data.msgList,
        inputVal,
        toView: 'msg-' + (this.data.msgList.length - 1)
      });
      new Request('Zyconcern/sendcontent').request(
        () => {
          return {
            openid: app.globalData.openid,
            uid: this.uid,
            contentText: this.data.userinput,
            userid: app.globalData.userid, //用户id
          }
        },
        (res) => {

        }
      );

      // this.sendSocketMessage(this.data.userinput)
      // wx.onSocketMessage(function(res){
      //   console.log(res)
      // });
    }

  },

  /**
   * 退回上一页
   */
  toBackClick: function () {
    wx.navigateBack({})
  },

  /**
   * swoole 聊天链接
   */
  //  sendSocketMessage:function(msg) {
  //   // if (socketOpen) {
  //     let data = {'msg':msg,'openid':2345};
  //     const obj =JSON.stringify(data);
  //     wx.sendSocketMessage({
  //       data:obj,
  //       success:function(res){
  //         console.log(res+'12343');
  //       }
  //     })
  //   // } else {
  //   //   socketMsgQueue.push(msg)
  //   // }
  // },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('页面隐藏了content' + this.intervalId);
    clearInterval(this.intervalId);
    this.intervalId = '';
  },



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }

})
